const wx2my = require('../../wx2my');

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');

var demo = new QQMapWX({
  key: '3NGBZ-BLF6N-RXPFK-SPZSN-2EXFE-KWFUW' //申请的Key

});

const api = require('../../utils/user_api_miniprogram.js');

const app = getApp();

let exitTimer = null

Page({
  data: {
    wrap: true,
    have_coupon: true,
    acceptRule: true,
    openAgain: 'openAgain',
    model: '',
    macno: '',
    phoneNum: '',
    marker: '',
    list: [],
    code: '',
    stopPull: '',
    markers: [],
    key: "3NGBZ-BLF6N-RXPFK-SPZSN-2EXFE-KWFUW",
    centerlat: 0,
    centerlon: 0,
    rfid: '',
    tradeid: '',
    tradeno: '',
    num: 1,
    minusStatus: 'disable',
    minusStatus1: 'normal',
    maxNum: 3,
    appCode: '',
    videoLink: '',
    swiperList: [],
    wrap2: true,
    showSplash: true, // 是否显示启动广告
    countdown: 3, // 倒计时秒数
    safeAreaInsets: {
      top: 0,
      bottom: 0
    },
    share: true,
    activity: {},
    helpList: [],
    ruleList: [],
    numberuser: 0,
    timer: null,
    endcountdown: "",
    resultmessage:"",
    mini_program_ads:"",
    mini_program_logo:"",
  },
  // 唤起分享面板
  showSharePanel() { 
    my.showSharePanel();
  },
  // 页面分享事件处理函数
  onShareAppMessage() {
    return {
      title: '邀请好友助力,免费玩无人机', // 标题
      desc: '为Ta助力!分享砍价免费玩，体验无人机', // 描述
      path: 'pages/share_help/share_help?InviteCode='+this.data.activity.invite_code, // 分享的小程序页面
      bgImgUrl: 'http://139.199.226.189/share.png', // 分享图片URL
      scImgUrl: 'http://139.199.226.189/share.png', // 分享图片URL
      success(res) {
        console.log('success', res);
      },
      fail(res) {
        console.log('fail', res)
      },
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */




  startCountdown() {
    this.countdownInterval = setInterval(() => {
      if (this.data.countdown <= 1) {
        this.hideSplash();
      } else {
        this.setData({
          countdown: this.data.countdown - 1
        });
      }
    }, 1000);
  },

  // 手动跳过广告
  handleSkipAd() {
    this.hideSplash();
  },
  // 隐藏启动广告
  hideSplash() {
    clearInterval(this.countdownInterval);
    this.setData({
      showSplash: false
    });
    // 恢复TabBar（如果之前隐藏了）
    my.showTabBar();

    // 恢复下拉刷新
    my.setCanPullDown({
      canPullDown: true
    });

  },
  // 手动跳过广告
  handleSplashTap() {
    this.setData({
      showSplash: false
    });
  },





  onUnload() {
    // 页面卸载时清除定时器
    clearInterval(this.countdownInterval);

  },
  onLoad: function (e) {
    // 启动小程序弹出分享砍价
    // this.shareOrder()

    this.getSwiper();
    // 获取安全区域（适配刘海屏）
    this.setData({
      safeAreaInsets: my.getSystemInfoSync().safeArea
    });

    // 隐藏TabBar（可选）
    my.hideTabBar();

    // 禁用下拉刷新
    my.setCanPullDown({
      canPullDown: false
    });

    // // 开始倒计时
    this.startCountdown();


    let that = this;
    this.getvideoLink();

    if (e.trade_id) {
      that.setData({
        paySus: false
      });
    }

    if (e.q) {
      if (e.q.indexOf('coupon_id') > 0) {
        let url = decodeURIComponent(e.q);
        let coupon_id = app.fm.getUrlParam('coupon_id', url);
        var msgToken = wx2my.getStorageSync('token');

        if (msgToken == '' || msgToken == null) {
          that.setData({
            wrap: false,
            coupon_id: coupon_id
          });
        } else {
          that.setData({
            wrap: true,
            coupon_id: coupon_id
          });
          that.get_coupon();
        }
      } else if (e.q.indexOf('macno') > 0) {
        let url = decodeURIComponent(e.q);
        let macno = app.fm.getUrlParam('macno', url);
        that.setData({
          macno: macno
        });
        that.get_status();
      } else if (e.q.indexOf('rfid') > 0) {
        let url = decodeURIComponent(e.q);
        let rfid = app.fm.getUrlParam('rfid', url);
        that.setData({
          rfid: rfid
        }); // that.get_status()
      } else if (e.q.indexOf('tradeid') > 0) {
        let url = decodeURIComponent(e.q);
        let tradeid = app.fm.getUrlParam('tradeid', url);
        that.setData({
          tradeid: tradeid
        });
      }
    }

    wx2my.getSystemInfo({
      success: function (res) {
        //设置map高度，根据当前设备宽高满屏显示
        that.setData({
          view: {
            Height: res.windowHeight,
            Width: res.windowWidth
          }
        });
      }
    });
  },
  onReady: function () {
    setTimeout(() => {
      this.permiss();
    }, 200);
  },
  shareClick(){
    this.setData({
      share: true,
    });
    this.showSharePanel()
  },
  closeShare() {
    this.setData({
      share: true,
    });
    // this.showSharePanel()
  },
  shareOrder() {
    let that = this;

    this.setData({
      share: false
    });
    app.wxRequest('getHelpActivity', {
      'token': wx2my.getStorageSync('token'),

    }, function (res) {
      console.log(res);
      if (res.data.code == 1) {
        that.setData({
          activity: res.data.data.activity,
          helpList: res.data.data.helpList,
          ruleList: res.data.data.ruleList,
          numberuser: res.data.data.numberuser,

        });
        that.startActivityCountdown(that.data.activity.end_time);
      }

    });
  },

  ReceiveCoupon(e){
    let that = this;
    const ruleId = e.currentTarget.dataset.ruleId; // 注意：属性名会自动转小写
    
    console.log('当前点击的 ruleId:', ruleId);
    
    console.log(e)

    app.wxRequest('userReceiveCoupon', {
      'token': wx2my.getStorageSync('token'),
      'ruleId': ruleId,
    }, function (res) {
      console.log(res);
      if (res.data.code == 1) {
      let ruleList=  that.data.ruleList.forEach(item=>{
          if(item.id == ruleId){
            item.is_finish = true
          }
        })
        that.setData({
          ruleList: res.data.data.ruleList,
        });
        wx2my.showToast({
          title: "领取成功！",
          icon: 'success',
          duration: 2000,

          success() {}

        });
      }else{
        // that.setData({
        //   resultmessage: res.data.msg,
        //   model:"message_temp"
        // })

        wx2my.showToast({
          title: res.data.msg,
          icon: 'error',
          duration: 2000,

          success() {}

        });

      }

    });

  },


  startActivityCountdown(endTime) {
    const end = new Date(endTime.replace(/-/g, '/')).getTime();
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }

    this.data.timer = setInterval(() => {
      const now = new Date().getTime();
      const distance = end - now;


      if (distance <= 0) {
        clearInterval(this.data.timer);
        this.setData({ endcountdown: "00:00:00" });
        return;
      }

      // 计算时、分、秒
      const hours = Math.floor(distance / (1000 * 60 * 60));
      const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((distance % (1000 * 60)) / 1000);

      // 格式化为两位数（如 5 → "05"）
      const formatTime = (num) => num < 10 ? `0${num}` : num;

      this.setData({
        endcountdown: `${formatTime(hours)}:${formatTime(minutes)}:${formatTime(seconds)}`
      });
      
    }, 1000);
  },
  
  //扫码获取优惠券
  get_coupon() {
    let that = this;
    app.wxRequest('receive_coupon', {
      'coupon_id': that.data.coupon_id
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        app.wxRequest('scan_code', {
          'coupon_id': that.data.coupon_id
        }, function (res) {
          console.log(res);

          if (res.data.code == 1) {
            that.setData({
              money: res.data.data.money,
              end_time: res.data.data.end_time,
              have_coupon: false
            });
          }
        });
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  // 同意规则
  bindAcceptRule: function (e) {
    let that = this;
    that.data.acceptRule = !that.data.acceptRule;

    if (that.data.acceptRule == true) {
      this.acceptRule = true;
    } else {
      this.acceptRule = false;
    }
  },
  // 授权登陆
  getUserProfile: function (e) {
    console.log(e);
    let that = this;

    if (that.data.acceptRule) {
      wx2my.showLoading({
        title: '正在登录'
      });
      app.fm.wx_login((flag, userInfo) => {
        if (flag == 2) {
          that.setData({
            wrap: true
          });

          if (that.data.coupon_id) {
            that.get_coupon();
          }

          wx2my.hideLoading();
        } else if (flag == 3) {
          wx2my.hideLoading();
        }
      }, app);
    } else {
      app.toast("请点击同意《用户协议》");
    }
  },
  onShow: function () {
    let that = this;
    api.user_location(function (res) {
      console.log(res);

      if (res.code == 1) {
        that.getLocation_fn();
      } else if (res.code == 0) {
        wx2my.showModal({
          title: '提示',
          content: '请前往设置界面打开权限！',

          success(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              wx2my.openSetting({
                success(data) {
                  console.log(data.authSetting["scope.userLocation"]);

                  if (data.authSetting["scope.userLocation"] == true) {
                    wx2my.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 2000,

                      success() {}

                    });
                  }
                }

              });
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }

        });
      }
    });
    that.get_phone();
  },


  /**播放视屏 */
  play(e) {
    //执行全屏方法  
    var videoContext = wx.createVideoContext('myvideo', this);
    videoContext.requestFullScreen();
    this.setData({
      fullScreen: true
    });
  },

  /**关闭视屏 */
  closeVideo() {
    //执行退出全屏方法


    this.setData({
      model: ''
    });

    // var videoContext = wx.createVideoContext('myvideo', this);
    // videoContext.exitFullScreen();
  },

  /**视屏进入、退出全屏 */
  fullScreen(e) {
    var isFull = e.detail.fullScreen; //视屏全屏时显示加载video，非全屏时，不显示加载video

    this.setData({
      fullScreen: isFull
    });
  },


  getvideoLink() {
    let that = this;
    app.wxRequest('getvideoLink', {}, function (res) {
      if (res.data.code == 1) {
        that.setData({
          videoLink: res.data.data
        });
      }
    });
  },
  getSwiper() {
    let that = this;
    app.wxRequest('getSwiper', {}, function (res) {


      if (res.data.code == 1) {

        console.log("-=-=-==--=", app.globalData.host +  JSON.parse(res.data.data.val).mini_program_ads);

        let imageString = JSON.parse(res.data.data.val).img
        // 分割字符串并去除空白项
        let imageUrls = imageString.split('\r\n').map(url => url.trim()).filter(url => url).map(url => app.globalData.host + url);

        // imageUrls = imageUrls.forEach(item=>{
        //   console.log(item)
        //   item =  "https://ygd.yunchuang.store"+item
        //  })

        // console.log("-=-=-==--=", imageUrls);

        that.setData({
          swiperList: imageUrls,
          mini_program_ads:app.globalData.host +  JSON.parse(res.data.data.val).mini_program_ads,
          mini_program_logo:app.globalData.host +  JSON.parse(res.data.data.val).mini_program_logo
        });
      }
    });
  },
  //获取客服电话
  get_phone() {
    let that = this;
    app.wxRequest('customer', {
      'type': 3
    }, function (res) {
      console.log(res.data.data.tel);

      if (res.data.code == 1) {
        that.setData({
          phoneNum: res.data.data.tel
        });
      }
    });
  },

  center(e) {
    let that = this;
    wx2my.navigateTo({
      url: '/pages/user_center/user_center'
    });
  },

  getLocation_fn: function () {
    let that = this;
    wx2my.getLocation({
      type: 'gcj02',

      success(res) {
        console.log(res);
        let markers = [];

        markers.push({
          id: -1,
          latitude: res.latitude,
          longitude: res.longitude,
          width: 30,
          height: 30,
          name: 'hello',
          iconPath: "/img/40.png",
          title: "",
          anchor: {
            x: .5,
            y: .5
          },
          // customCallout:{
          //   display:"ALWAYS",
          // }
          label: {
            content: "附近柜子 >",
            color: "#000000",
            bgColor: "#ffffff",
            fontWeight: "700",
            display: "ALWAYS",
            fontSize: "12",
            borderRadius: "5",
            padding: "10"
          }
        });


        that.setData({
          latitude: res.latitude,
          longitude: res.longitude,
          centerlat: res.latitude,
          centerlon: res.longitude,
          markers: markers
        });
        console.log(res.latitude);
        that.get_markers(); //获取标注点
      },

      fail(e) {}

    });
  },
  get_markers: function () {
    let that = this;
    let markers = that.data.markers;
    console.log(that);
    app.wxRequest('nearby', {
      'lat': that.data.latitude,
      'lng': that.data.longitude
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let markers = that.data.markers;
        let list = res.data.data;
        console.log(list);
        list.forEach((item, index) => {
          markers.push({
            id: index,
            latitude: item.lat,
            longitude: item.lng,
            width: 30,
            height: 30,
            title: "",
            anchor: {
              x: .5,
              y: .5
            }
          });
        });


        console.log("----------", markers);
        that.setData({
          shop: list,
          markers: markers
        });
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  //点击merkers
  markertap(e) {
    console.log(e);

    if (e.markerId == -1) {
      wx2my.navigateTo({
        url: '/pages/near_store/near_store?centerlat=' + this.data.centerlat + "&centerlon=" + this.data.centerlon
      });
    }

    if (e.markerId < 0) {
      return false;
    } else {
      console.log(this.data.shop[e.markerId]);
      this.setData({
        marker_msg: true,
        using_show: false,
        current_marker: this.data.shop[e.markerId]
      });
    }
  },

  controltap(e) {
    var that = this; //重新定位
    //重新定位

    let mapCtx = my.createMapContext("map");
    var latitude, longitude;
    mapCtx.getCenterLocation({
      success: function (res) {
        latitude = res.latitude;
        longitude = res.longitude;
      }
    });
    // //获取当前地图的中心经纬度
    // mapCtx.includePoints({
    //     padding:[10],
    //     points:[{
    //         latitude:latitude,
    //         longitude:longitude
    //     }]
    // })
    // mapCtx.translateMarker({
    //     markerId: -1,
    //     autoRotate: true,
    //     duration: 100,
    //     destination: {
    //         latitude:latitude,
    //         longitude:longitude,
    //     },
    //     animationEnd() {
    //         console.log('animation end')
    //     }
    // })

    // mapCtx.moveToLocation();
  },

  destination(e) {
    //导航
    console.log(e);
    wx2my.openLocation({
      latitude: e.currentTarget.dataset.lat * 1,
      longitude: e.currentTarget.dataset.lng * 1,
      scale: 28,
      name: e.currentTarget.dataset.address,
      address: e.currentTarget.dataset.address
    });
  },

  //判断用户租借状态
  //-22 有进行中的订单 -33 有一个未支付订单   -55 暂无空柜可租借 -44暂不可租借 您有两个正在进行中的订单
  get_status() {
    let that = this;
    app.wxRequest('rentToyCar', {
      'token': wx2my.getStorageSync('token'),
      'macno': that.data.macno ? that.data.macno : '',
      'rfid': that.data.rfid ? that.data.rfid : ''
    }, function (res) {
      console.log(res);

      if (res.data.code == -22) {
        that.setData({
          model: 'underway'
        });
      } else if (res.data.code == -33) {
        that.setData({
          model: 'haveOrder',
          macno: ''
        });
      } else if (res.data.code == -44) {
        that.setData({
          model: 'no_rent',
          macno: ''
        });
      } else if (res.data.code == -55) {
        that.setData({
          model: 'no_car',
          macno: ''
        });
      } else if (res.data.code == 1) {
        that.setData({
          macno: that.data.macno
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  bindcallouttap(e) {
    console.log(this.data.centerlat);
    let mapCtx = my.createMapContext('map');
    mapCtx.getCenterLocation({
      success: res => {
        let longitude = res.longitude.toFixed(6);
        let latitude = res.latitude.toFixed(6);
        this.setData({
          centerlat: latitude,
          centerlon: longitude
        });
        wx2my.navigateTo({
          url: '/pages/near_store/near_store?centerlat=' + this.data.centerlat + "&centerlon=" + this.data.centerlon
        });
      }
    });
  },
  get_toRentStatus() {
    let that = this;
    app.wxRequest('rentToyCar', {
      'token': wx2my.getStorageSync('token'),
      'macno': that.data.macno ? that.data.macno : '',
      'rfid': that.data.rfid ? that.data.rfid : ''
    }, function (res) {
      console.log(res);

      if (res.data.code == -22) {
        that.setData({
          model: 'underway'
        });
      } else if (res.data.code == -33) {
        that.setData({
          model: 'haveOrder',
          macno: ''
        });
      } else if (res.data.code == -44) {
        that.setData({
          model: 'no_rent',
          macno: ''
        });
      } else if (res.data.code == -55) {
        that.setData({
          model: 'no_car',
          macno: ''
        });
      } else if (res.data.code == 1) {
        if (that.data.macno != '') {
          wx2my.navigateTo({
            url: '/pages/select_car/select_car?macno=' + that.data.macno
          });
        } else if (that.data.rfid != '') {
          wx2my.navigateTo({
            url: '/pages/select_car/select_car?rfid=' + that.data.rfid
          });
        }

        that.setData({
          macno: '',
          rfid: ''
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  getTradeTuan() {
    let that = this;
    app.wxRequest('get_trade_tuan', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.tradeid
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        that.setData({
          macno: '',
          rfid: '',
          maxNum: res.data.data.nowTotal,
          tradeno: res.data.data.trade.tradeno
        });
        that.setData({
          model: 'JoinTrade'
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  //租借
  toRent(e) {
    let that = this;
    let msgToken = wx2my.getStorageSync('token');

    if (msgToken == '' || msgToken == null) {
      that.setData({
        wrap: false
      });
    } else if (that.data.tradeid != '') {
      that.getTradeTuan();
    } else if (that.data.macno != '') {
      that.get_toRentStatus();
    } else if (that.data.rfid != '') {
      that.get_toRentStatus();
    } else if (that.data.tradeid != '') {
      that.get_toRentStatus();
    } else {
      wx2my.scanCode({
        success: res => {
          console.log(res);
          var res = res.result;

          if (res.indexOf('macno') < 0 && res.indexOf('rfid') < 0 && res.indexOf('tradeid') < 0) {
            wx2my.showToast({
              icon: 'none',
              title: '二维码无效'
            });
          } else if (res.indexOf('macno') > 0) {
            let macno = app.fm.getUrlParam('macno', res);
            wx2my.setStorageSync('macno', macno);
            that.setData({
              macno: macno,
              rfid: ""
            });
            that.get_toRentStatus();
          } else if (res.indexOf('rfid') > 0) {
            let rfid = app.fm.getUrlParam('rfid', res);
            wx2my.setStorageSync('rfid', rfid);
            that.setData({
              rfid: rfid,
              macno: ""
            });
            that.get_toRentStatus();
          } else if (res.indexOf('tradeid') > 0) {
            let tradeid = app.fm.getUrlParam('tradeid', res);
            wx2my.setStorageSync('tradeid', tradeid);
            that.setData({
              tradeid: tradeid,
              macno: ""
            });
            that.getTradeTuan();
          }
        }
      });
    }
  },

  //归还
  toReturn(e) {
    let that = this;
    let msgToken = wx2my.getStorageSync('token');

    if (msgToken == '' || msgToken == null) {
      that.setData({
        wrap: false
      });
    } else {
      wx2my.navigateTo({
        url: '/pages/user_order/user_order'
      });
    }
  },

  //归还玩具打开柜门
  back_toy() {
    let that = this;
    app.wxRequest('back_toy', {
      'token': wx2my.getStorageSync('token'),
      'macno': that.data.macno
    }, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        let yun_id = res.data.data.yun_id;
        that.setData({
          model: 'open_sus',
          yun_id: yun_id
        });
        that.get_backStatus();
      } else if (res.data.code == -22) {
        that.setData({
          model: 'back_noOrder',
          macno: ''
        });
      } else if (res.data.code == -33) {
        that.setData({
          model: 'no_chest',
          macno: ''
        });
      } else if (res.data.code == -44) {
        that.setData({
          model: 'open_fail',
          yun_id: res.data.data.yun_id
        });
      } else if (res.data.code == -55) {
        that.setData({
          model: 'have_return',
          macno: ''
        });
      } else if (res.data.code == -77) {
        that.setData({
          model: 'back_mistake',
          macno: ''
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  //归还状态
  get_backStatus() {
    let that = this;
    app.wxRequest('polling_back_toy', {
      'yun_id': that.data.yun_id
    }, function (res) {
      if (res.data.code == 1) {
        app.toast(res.data.msg);
        that.setData({
          macno: '',
          model: 'return_sus',
          disinfect_time: res.data.data.disinfect_time
        });
        setTimeout(() => {
          that.setData({
            model: 'pay_sus'
          });
        }, 3000);
        wx2my.hideLoading();
      } else if (res.data.code == 0) {
        wx2my.showLoading({
          title: '归还中',
          mask: true
        });
        that.data.stopPull = setTimeout(function () {
          that.get_backStatus();
        }, 2000);
      } else if (res.data.code == 2) {
        let trade_id = res.data.data.trade_id;
        that.setData({
          macno: '',
          model: 'return_sus',
          disinfect_time: res.data.data.disinfect_time
        });
        setTimeout(() => {
          that.setData({
            model: ''
          });
          wx2my.navigateTo({
            url: '/pages/pay_order/pay_order?trade_id=' + trade_id
          });
        }, 2000);
        wx2my.hideLoading();
      } else if (res.data.code == -11) {
        that.setData({
          model: 'power_fail'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -22) {
        that.setData({
          model: 'hand_mistake'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -50) {
        that.setData({
          model: 'hand_fail'
        });
        wx2my.hideLoading();
      } else if (res.data.code == -60) {
        that.setData({
          model: 'order_noYour',
          macno: ''
        });
        wx2my.hideLoading();
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
        wx2my.hideLoading();
      }
    });
  },

  cancel() {
    this.setData({
      wrap: true,
      rfid: '',
      macno: '',
      tradeid: '',
      tradeno: ''
    });
  },

  //联系客服总平台
  toCall() {
    let that = this;


    wx2my.navigateTo({
      url: '/pages/user_join/user_join'
    });

    // app.wxRequest('customer', {}, function (res) {
    //   console.log(res);

    //   if (res.data.code == 1) {
    //     let phone = res.data.data.tel;
    //     wx2my.showModal({
    //       title: '温馨提示',
    //       content: '拨打电话:' + res.data.data.tel,

    //       success(res) {
    //         if (res.confirm) {
    //           wx2my.makePhoneCall({
    //             phoneNumber: phone
    //           });
    //         } else if (res.cancel) {
    //           console.log('用户点击取消');
    //         }
    //       }

    //     });
    //   }
    // });
  },

  //故障联系客服
  tel() {
    let that = this;
    wx2my.showModal({
      title: '提示',
      content: '拨打电话:' + that.data.phoneNum,

      success(res) {
        if (res.confirm) {
          wx2my.makePhoneCall({
            phoneNumber: that.data.phoneNum
          });
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }

    });
  },

  //开门失败重新开门
  openAgain() {
    let that = this;
    that.setData({
      model: '',
      openAgain: ''
    });
    that.get_doorOpenstatus();
  },

  get_doorOpenstatus() {
    let that = this;
    app.wxRequest('reopen_door', {
      'token': wx2my.getStorageSync('token'),
      'yun_id': that.data.yun_id
    }, function (res) {
      console.log(res);

      if (res.data.code == 100) {
        that.get_backStatus();
        that.setData({
          model: 'open_sus'
        });
      } else if (res.data.code == -100) {
        that.setData({
          model: 'open_fail'
        });
      } else {
        that.setData({
          model: '',
          macno: ''
        });
        app.toast(res.data.msg);
      }

      that.setData({
        openAgain: 'openAgain'
      });
    });
  },

  howToUse() {
    this.setData({
      model: 'video'
    });
  },
  del() {
    this.setData({
      have_coupon: true,
      wrap: true,
      model: '',
      macno: '',
      rfid: '',
      tradeid: '',
      tradeno: ''
    });
  },

  lookOther() {
    this.setData({
      model: ''
    });
  },

  //有一个未支付的订单
  toOrder() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 0
    });
  },

  //有一个体验的订单正在进行
  toLookOrder() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 3
    });
  },

  //订单支付成功查看订单
  underwayOrder() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 3
    });
  },

  //正在进行中两个订单
  lookContinue() {
    this.setData({
      model: '',
      macno: ''
    });
    wx2my.navigateTo({
      url: '/pages/user_order/user_order?typeid=' + 3
    });
  },

  //继续租借
  again() {
    let that = this;
    this.setData({
      model: ''
    });
    wx2my.navigateTo({
      url: '/pages/select_car/select_car?macno=' + that.data.macno + '&marker=' + 1
    });
    this.setData({
      macno: ''
    });
  },

  //用户协议
  toAgree() {
    wx2my.navigateTo({
      url: '/pages/user_agreement/user_agreement'
    });
  },

  //充值中心
  apply() {
    let that = this;

    if (!app.fm.gain('token')) {
      that.setData({
        wrap: false
      });
    } else {
      that.setData({
        macno: ''
      });
      wx2my.navigateTo({
        url: '/pages/recharge/recharge'
      });
    }
  },

  onUnload: function () {
    let that = this;
    clearTimeout(that.data.stopPull);
    that.setData({
      model: ''
    });

    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
  },
  //视图改变
  bindchangeTap: function (ev) {
    let that = this; // if (ev.type == "end") {
    //   that.refreshMap();
    // }

    let mapCtx = my.createMapContext('map');
    mapCtx.getCenterLocation({
      success: function (res) {
        let lat = res.latitude;
        let lng = res.longitude;
        that.setData({
          ["markers[0].latitude"]: lat,
          //修改数组对象中的某一项
          ["markers[0].longitude"]: lng
        });
      }
    });
  },

  queding() {
    this.setData({
      model: ''
    });

    if (wx2my.getStorageSync('wrap') == true) {
      this.setData({
        wrap2: true
      });
    } else {
      this.setData({
        wrap2: false
      });
      return;
    }

    let that = this;
    app.wxRequest('add_trade_tuan', {
      'token': wx2my.getStorageSync('token'),
      'trade_id': that.data.tradeid,
      'num': that.data.num
    }, function (res) {
      console.log(res);
      that.setData({
        macno: '',
        rfid: '',
        tradeid: ''
      });

      if (res.data.code == 1) {
        that.setData({
          model: 'JoinTradeSuccess'
        });
      } else {
        app.toast(res.data.msg);
        that.setData({
          macno: ''
        });
      }
    });
  },

  cancel() {
    this.setData({
      model: ''
    });
    this.setData({
      macno: '',
      rfid: '',
      tradeid: ''
    });
  },

  //事件处理函数

  /*点击减号*/
  bindMinus() {
    var num = this.data.num;

    if (num > 1) {
      num--;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*点击加号*/
  bindPlus() {
    var num = this.data.num;
    console.log(num);

    if (num < this.data.maxNum) {
      num++;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  /*输入框事件*/
  bindManual(e) {
    var num = e.detail.value;
    console.log(e);

    if (num > this.data.maxNum) {
      num = this.data.maxNum;
    }

    if (num < 1) {
      num = 1;
    }

    var minusStatus = num > 1 ? 'normal' : 'disable';
    var minusStatus1 = num < this.data.maxNum ? 'normal' : 'disable';
    this.setData({
      num: num,
      minusStatus: minusStatus,
      minusStatus1: minusStatus1
    });
  },

  //绑定微信手机号
  getPhoneNumber(e) {
    console.log(e);

    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      let that = this;
      let msg = e;
      that.bindPhone(msg);
    } else {
      app.toast('请绑定手机号');
    }
  },

  bindPhone(msg) {
    var that = this;
    app.wxRequest('get_user_phone', {
      'type': 'weixin',
      'encryptedData': encodeURIComponent(msg.detail.encryptedData),
      'code': that.data.appCode,
      'iv': encodeURIComponent(msg.detail.iv)
    }, function (res) {
      console.log(res);

      if (res.data.code = 1) {
        let userInfo = res.data.data.phone ? JSON.parse(res.data.data.phone) : '';
        console.log(userInfo, "asdfgasdfasdgasdgasdg");

        if (!userInfo) {
          app.toast('手机号获取失败,请重新获取');
        } else {
          app.wxRequest('edit', {
            'account': userInfo
          }, function (res) {
            console.log(res);

            if (res.data.code == 1) {
              that.setData({
                wrap2: true
              });
              wx2my.setStorageSync('wrap', true);
            } else if (res.data.code == -1005) {
              app.toast(res.data.msg);
              that.setData({
                wrap2: true
              });
              wx2my.setStorageSync('wrap', true);
            }
          });
        }
      } else {
        app.toast(res.data.msg);
      }
    });
  },

  //是否绑定 手机号 
  permiss(e) {
    let that = this;
    app.wxRequest('profile', {}, function (res) {
      console.log(res);

      if (res.data.code == 1) {
        if (res.data.data.account == '' && that.data.auth == 1) {
          //未绑定
          console.log(res.data.data.account);
        }

        if (!that.data.appCode) {

          my.getAuthCode({
            scopes: ['auth_base'],
            success: function (e) {
              console.log("111getAuthCode11", e);
              let code = e.authCode;
              that.setData({
                appCode: code
              });
            }
          })

        }
      } else {
        wx2my.showToast({
          icon: 'none',
          title: res.data.msg,
          duration: 2000
        });
      }
    });
  },


  lookOther() {
    wx2my.navigateTo({
      url: '/pages/near_store/near_store?centerlat=' + this.data.centerlat + "&centerlon=" + this.data.centerlon
    });
  }

});